package ants.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import weibo4j.Oauth;
import weibo4j.examples.oauth2.Log;
import weibo4j.http.AccessToken;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;

public class OAuth4Code {
	public static void main(String [] args) throws Exception{
		Oauth oauth = new Oauth();
		BareBonesBrowserLaunch.openURL(oauth.authorize("code"));
		System.out.println(oauth.authorize("code"));
//		readContentFromGet(oauth.authorize("code"));
		System.out.print("Hit enter when it's done.[Enter]:");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String code = br.readLine();
		Log.logInfo("code: " + code);
		try{			
			
			System.out.println(oauth.getAccessTokenByCode(code));
		} catch (WeiboException e) {
			if(401 == e.getStatusCode()){
				Log.logInfo("Unable to get the access token.");
			}else{
				e.printStackTrace();
			}
		}
	}
	
	public static AccessToken getAccessToken(String code){
		Oauth oauth = new Oauth();
		AccessToken accessToken = null;
		try {
			accessToken=oauth.getAccessTokenByCode(code);
			System.out.println(accessToken);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return accessToken;
	}
	
	public String hello (String code){
		return "hello2"+code;
	}
	public Map hello (Map param){
		param.put("name", param.get("user_name")+"2");
		param.put("code", param.get("password")+"2");
		return param;
	}
	public User hello2 (Map param){
		User u=new User();
		u.setFamilyName((String)param.get("user_name"));
		u.setFirstName((String)param.get("password"));
		return u;
	}
	public static void readContentFromGet(String getURL) throws IOException
	{
	// 拼凑get请求的URL字串，使用URLEncoder.encode对特殊和不可见字符进行编码
	URL getUrl = new URL(getURL);
	// 根据拼凑的URL，打开连接，URL.openConnection函数会根据URL的类型，
	// 返回不同的URLConnection子类的对象，这里URL是一个http，因此实际返
	//回的是HttpURLConnection
	HttpURLConnection connection = (HttpURLConnection) getUrl
	.openConnection();
	// 进行连接，但是实际上get request要在下一句的connection.getInputStream()
	//函数中才会真正发到服务器
	connection.connect();
	// 取得输入流，并使用Reader读取
	BufferedReader reader = new BufferedReader(new InputStreamReader(
	connection.getInputStream(), "utf-8"));
	System.out.println("=============================");
	System.out.println("Contents of get request");
	System.out.println("=============================");
	String lines;
	while ((lines = reader.readLine()) != null)
	{
	System.out.println(lines);
	}
	reader.close();
	// 断开连接
	connection.disconnect();
	System.out.println("=============================");
	System.out.println("Contents of get request ends");
	System.out.println("=============================");
	}

}
